package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;


/**
 * 权限过滤控件    如果用户没有访问  value 参数的权限，那么就不渲染该标签内的html代码
 * type:验证类型  默认为 AUTH 访问路径的访问权限
 * 		LOGIN 是否登录
 * 		ROLE 角色验证
 * 
 * @author Feng J
 *
 */
public class TopAuth extends TopTemplateModel{
	
	private static final long serialVersionUID = 1L;
	
	public final static String TAG ="auth";

	private String value;
	
	private String type;
	
	private boolean render = false;
	
	private BaseController controller;
	
	public TopAuth(BaseController controller){
		this.controller = controller;
	}
	
	private void initPara(@SuppressWarnings("rawtypes") Map para, Environment env) throws TemplateException{
		value = getStrPara("value", para, env);
		type = getStrPara("type", para, env);
		if(StringUtil.isNull(type) || type.equals("AUTH")){
			render = controller.getUserSession()==null?false:controller.getUserSession().auth(value);
		}else{
			if(type.equals("LOGIN")){
				render = controller.getUserSession()!=null;
			}
		}
		
		// TODO 角色的权限判断
	}

	@Override
	public void execute(Environment arg0, @SuppressWarnings("rawtypes") Map arg1, TemplateModel[] arg2,
			TemplateDirectiveBody arg3) throws TemplateException, IOException {
		initPara(arg1, arg0);
		Writer w = arg0.getOut();
		if(render)
			arg3.render(w);
	}

}
